package com.test.testauth.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author ：wang qiang
 * @date ：Created 2024/8/1 18:41
 * @description：获取Bean上下文对象
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public SpringContextUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        try {
            return getApplicationContext().getBean(beanName);
        } catch (Exception var2) {
            return null;
        }
    }

    public static Map<String, Object> getBeanByType(Class clazz) {
        try {
            return getApplicationContext().getBeansOfType(clazz);
        } catch (Exception var2) {
            return null;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            return getApplicationContext().getBean(clazz);
        } catch (Exception var2) {
            return null;
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        try {
            return getApplicationContext().getBean(name, clazz);
        } catch (Exception var3) {
            return null;
        }
    }

}
